package com.dd.seckill.cluster.utils.redisdatainit;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.commands.JedisCommands;

import java.io.PrintWriter;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.dd.seckill.cluster.utils.redisdatainit.UserTokenInitializer.createRedisConnection;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/7 11:40
 * @Description 秒杀商品信息预热工具类 - 集群版
 */
public class SeckillGoodsWarmUper {

    // MySQL 连接配置
    private static final String MYSQL_URL = "jdbc:mysql://localhost:3306/dd_seckill?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    private static final String MYSQL_USER = "root";
    private static final String MYSQL_PASSWORD = "root";

    // Redis 连接配置
    private static final String REDIS_HOST = "REDIS_HOST";
    private static final int REDIS_PORT = 28421;
    private static final String REDIS_PASSWORD = "REDIS_PASSWORD";
    private static final String REDIS_USER = "redis";

    // Redis Key 前缀
    private static final String GOODS_KEY_PREFIX = "seckill:goods:";
    private static final String STOCK_KEY_PREFIX = "seckill:stock:";
    private static final String USER_SET_KEY_PREFIX = "seckill:success:users:";

    public static void main(String[] args) {
        executeWarmUp();
    }

    private static void executeWarmUp() {
        System.out.println("开始执行秒杀商品预热任务..." + LocalDateTime.now());

        Connection dbConn = null;
        JedisCommands jedis = null;
        PrintWriter fileWriter = null;

        try {
            // 1. 建立数据库连接
            System.out.println("正在连接数据库...");
            dbConn = DriverManager.getConnection(MYSQL_URL, MYSQL_USER, MYSQL_PASSWORD);

            // 2. 建立Redis连接（尝试多种连接方式）
            System.out.println("正在连接Redis...");
            jedis = createRedisConnection();

            // 3. 执行预热任务 - 预热所有8个商品
            warmUpSeckillGoods(dbConn, jedis);

        } catch (Exception e) {
            System.err.println("预热任务执行失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 4. 关闭资源
            if (dbConn != null) {
                try {
                    dbConn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (jedis != null) {
                if (jedis instanceof Jedis) {
                    ((Jedis) jedis).close();
                } else if (jedis instanceof JedisCluster) {
                    ((JedisCluster) jedis).close();
                }
            }
        }

        System.out.println("预热任务执行完成！");
    }

    /**
     * 预热所有秒杀商品数据到Redis集群
     */
    private static void warmUpSeckillGoods(Connection conn, JedisCommands jedis) {
        String sql = "SELECT id, goods_name, original_price, seckill_price, " +
                "initial_stock, available_stock, start_time, end_time " +
                "FROM seckill_goods " +
                "WHERE available_stock > 0";

        try (PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            int processedCount = 0;

            while (rs.next()) {
                long goodsId = rs.getLong("id");
                String goodsName = rs.getString("goods_name");
                double originalPrice = rs.getDouble("original_price");
                double seckillPrice = rs.getDouble("seckill_price");
                int availableStock = rs.getInt("available_stock");
                Timestamp startTime = rs.getTimestamp("start_time");
                Timestamp endTime = rs.getTimestamp("end_time");

                // 使用hash tag确保相关key在同一slot
                String goodsKey = GOODS_KEY_PREFIX + "{" + goodsId + "}";
                String stockKey = STOCK_KEY_PREFIX + "{" + goodsId + "}";
                String successUserSetKey = USER_SET_KEY_PREFIX + "{" + goodsId + "}";

                // 存储商品信息到Hash
                Map<String, String> goodsData = new HashMap<>();
                goodsData.put("id", String.valueOf(goodsId));
                goodsData.put("goodsName", goodsName);
                goodsData.put("originalPrice", String.valueOf(originalPrice));
                goodsData.put("seckillPrice", String.valueOf(seckillPrice));
                goodsData.put("startTime", startTime.toString());
                goodsData.put("endTime", endTime.toString());
                goodsData.put("availableStock", String.valueOf(availableStock));

                jedis.hmset(goodsKey, goodsData);

                // 存储库存到String
                jedis.set(stockKey, String.valueOf(availableStock));

                // 清空并初始化用户集合
                jedis.del(successUserSetKey);

                processedCount++;
                System.out.println("✓ 预热成功: ID=" + goodsId + ", 名称=" + goodsName +
                        ", 库存=" + availableStock);
            }

            System.out.println("共处理 " + processedCount + " 个商品");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}